import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class RxDartDemo extends StatelessWidget {
  const RxDartDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('RxDartDemo'),
        elevation: 0.0,
      ),
      body: RxDartDemoHome(),
    );
  }
}

class RxDartDemoHome extends StatefulWidget {
  const RxDartDemoHome({super.key});

  @override
  State<RxDartDemoHome> createState() => _RxDartDemoHomeState();
}

class _RxDartDemoHomeState extends State<RxDartDemoHome> {
  late PublishSubject<String> _textFieldSubject;

  @override
  void initState() {
    super.initState();
    // Stream.periodic(Duration(seconds: 3), (x)=>x.toString());

    // Stream.fromIterable([1, 2, 3])
    // .throttle((_) => TimerStream(true, Duration(seconds: 1)))
    // .listen(print); 

    // PublishSubject<String> _subject = PublishSubject<String>(); //listen 1 始终保持监听 其余监听不是
    // BehaviorSubject<String> _subject = BehaviorSubject<String>(); //所有listen 始终保持监听  _subject.add('hello'); 之后监听 倒叙输出
    // ReplaySubject<String> _subject = ReplaySubject<String>(maxSize: 2); //限制个数
    
    // _subject.listen((data) {
    //   print('listen 1: $data');
    // });
    // _subject.add('hello');
    // _subject.listen((data) { 
    //   print('listen 2: ${data.toUpperCase()}');
    // });
    // _subject.add('hola');

    // _subject.close();

    //监听文本框输入和提交
    _textFieldSubject = PublishSubject<String>();
    _textFieldSubject
    // .map((item) => 'item: $item') //数据转换 打印多加了几个字符
    // .where((item) => false) //条件判断
    .debounceTime(Duration(milliseconds: 500)) //停止输入后 0.5秒 监听
    .listen((value) {
      print('$value');
    });
    
  }

  @override
  void dispose() {
    super.dispose();
    _textFieldSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        primaryColor: Colors.black
      ),
      child: TextField(
        onChanged: ((value) {
          _textFieldSubject.add('input: $value');
        }),
        onSubmitted: ((value) {
          _textFieldSubject.add('submit: $value');
        }),
        decoration: const InputDecoration(
          labelText: 'Title',
          filled: true
        ),
      ),
    );
  }
}